package com.example.udpLearn.udp4;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

/**
 * 客户端多次发送数据，服务端接收数据，并返回数据给客户端：服务端
 */
public class Server {
    public static void main(String[] args) throws IOException {

        System.out.println("服务端启动...");

        DatagramSocket socket = new DatagramSocket(9999);

        while (true) {
            byte[] serverReceive = new byte[1024 * 64];
            DatagramPacket packetReceive = new DatagramPacket(serverReceive, serverReceive.length);
            socket.receive(packetReceive);
            System.out.println("地址：" + packetReceive.getAddress());
            System.out.println("端口：" + packetReceive.getPort());
            System.out.println("服务端接收到的数据：" + new String(packetReceive.getData(), 0, packetReceive.getLength()));
            System.out.println("========================");

            /**
             * 给客户端发送的数据
             */
            byte[] serverSend = "已经接收到了数据".getBytes();
            DatagramPacket packet = new DatagramPacket(serverSend, serverSend.length, packetReceive.getAddress(), packetReceive.getPort());
            socket.send(packet);
        }


    }
}
